using UnityEngine;
using System.Collections.Generic;
using System.Diagnostics;
using System;
using Debug = UnityEngine.Debug;
using Random = UnityEngine.Random;

public class MapManager : MonoBehaviour
{
    [Header("系统引用")]
    [SerializeField] private GameManager gameManager;
    [SerializeField] private DataManager dataManager;
    //todo：构建完UIManager后引入此处使用
    //[SerializeField] private UIManager uiManager;
    private GameState gameState;
    [Header("地图配置")]
    public MapConfig mapConfig;

    private MapData currentMap;
    private string currentNodeId;

    //时间
    public System.Action<MapData> OnMapChanged;

    private void Awake()
    {
        if (gameManager == null) gameManager = FindObjectOfType<GameManager>();
        if (dataManager == null) dataManager = FindObjectOfType<DataManager>();
        //if (uiManager == null) uiManager = FindObjectOfType<UIManager>();
        gameState = FindObjectOfType<GameState>();
    }

    /// <summary>
    /// 初始化新地图
    /// </summary>
    public void InitializeNewMap(int actNumber)
    {
        currentMap = mapConfig.GenerateMap(actNumber);
        currentNodeId = currentMap.startNodeId;

        // 更新游戏状态
        gameState.currentMapNode = currentNodeId;

        Debug.Log($"初始化第{actNumber}幕地图，起始节点: {currentNodeId}");

        OnMapChanged?.Invoke(currentMap);
    }

    /// <summary>
    /// 加载已有地图
    /// </summary>
    public void LoadExistingMap(MapData savedMap, string currentPosition)
    {
        currentMap = savedMap;
        currentNodeId = currentPosition;
    }

    /// <summary>
    /// 获取可到达的相邻节点
    /// </summary>
    public List<MapNode> GetReachableNodes()
    {
        MapNode currentNode = currentMap.GetNode(currentNodeId);
        List<MapNode> reachableNodes = new List<MapNode>();

        foreach (string neighborId in currentNode.neighborIds)
        {
            MapNode neighbor = currentMap.GetNode(neighborId);
            if (neighbor != null && !neighbor.isVisited)
            {
                reachableNodes.Add(neighbor);
            }
        }

        return reachableNodes;
    }

    /// <summary>
    /// 移动到指定节点
    /// </summary>
    public void MoveToNode(string nodeId)
    {
        MapNode targetNode = currentMap.GetNode(nodeId);
        if (targetNode == null)
        {
            Debug.LogError($"目标节点不存在: {nodeId}");
            return;
        }

        // 验证是否可达
        if (!IsNodeReachable(nodeId))
        {
            Debug.LogWarning($"节点不可达: {nodeId}");
            return;
        }

        // 标记当前节点为已访问
        MapNode currentNode = currentMap.GetNode(currentNodeId);
        currentNode.isVisited = true;

        // 更新当前位置
        currentNodeId = nodeId;
        gameState.currentMapNode = currentNodeId;

        // 触发节点事件
        TriggerNodeEvent(targetNode);

        Debug.Log($"移动到节点: {targetNode.nodeName} ({targetNode.nodeType})");
    }

    /// <summary>
    /// 验证节点是否可达
    /// </summary>
    private bool IsNodeReachable(string nodeId)
    {
        MapNode currentNode = currentMap.GetNode(currentNodeId);
        return currentNode.neighborIds.Contains(nodeId);
    }

    /// <summary>
    /// 触发节点事件
    /// </summary>
    private void TriggerNodeEvent(MapNode node)
    {
        switch (node.nodeType)
        {
            case NodeType.Learning:
                StartLearningBattle(node);
                break;

            case NodeType.ChallengeTeacher:
                StartTeacherBattle(node);
                break;

            case NodeType.Market:
                OpenMarket(node);
                break;

            case NodeType.Dormitory:
                OpenDormitory(node);
                break;

            case NodeType.Event:
                TriggerRandomEvent(node);
                break;

            case NodeType.Boss:
                StartBossBattle(node);
                break;
        }

        // 保存游戏状态
        gameManager.SaveGame();
    }

    /// <summary>
    /// 开始学习战斗
    /// </summary>
    private void StartLearningBattle(MapNode node)
    {
        // 配置战斗参数
        BattleConfig battleConfig = new BattleConfig
        {
            enemyIds = node.enemyIds,
            isBossBattle = false,
            isEliteBattle = false,
            nodeType = NodeType.Learning
        };

        gameManager.EnterBattle(battleConfig);
    }

    /// <summary>
    /// 开始老师战斗
    /// </summary>
    private void StartTeacherBattle(MapNode node)
    {
        BattleConfig battleConfig = new BattleConfig
        {
            enemyIds = node.enemyIds,
            isBossBattle = false,
            isEliteBattle = true,
            nodeType = NodeType.ChallengeTeacher
        };

        gameManager.EnterBattle(battleConfig);
    }

    /// <summary>
    /// 开始Boss战斗
    /// </summary>
    private void StartBossBattle(MapNode node)
    {
        // 检查学分是否足够
        if (!gameState.canChallengeBoss)
        {
            //uiManager.ShowMessage("学分不足，无法挑战期末考试！");
            return;
        }

        BattleConfig battleConfig = new BattleConfig
        {
            enemyIds = node.enemyIds,
            isBossBattle = true,
            isEliteBattle = false,
            nodeType = NodeType.Boss
        };

        gameManager.EnterBattle(battleConfig);
    }

    /// <summary>
    /// 打开集市
    /// </summary>
    private void OpenMarket(MapNode node)
    {
        //uiManager.OpenShopUI();
    }

    /// <summary>
    /// 打开宿舍
    /// </summary>
    private void OpenDormitory(MapNode node)
    {
        //uiManager.OpenRestUI();
    }

    /// <summary>
    /// 触发随机事件
    /// </summary>
    private void TriggerRandomEvent(MapNode node)
    {
        string randomEventId = node.eventIds[Random.Range(0, node.eventIds.Count)];
        //uiManager.OpenEventUI(randomEventId);
    }

    /// <summary>
    /// 检查是否到达Boss节点
    /// </summary>
    public bool IsAtBossNode()
    {
        MapNode currentNode = currentMap.GetNode(currentNodeId);
        return currentNode.nodeType == NodeType.Boss;
    }

    /// <summary>
    /// 进入下一幕
    /// </summary>
    public void AdvanceToNextAct()
    {
        int nextAct = currentMap.actNumber + 1;
        if (nextAct <= mapConfig.totalActs)
        {
            InitializeNewMap(nextAct);
            //uiManager.ShowMessage($"进入第{nextAct}幕！");
        }
        else
        {
            // 游戏通关
            gameManager.HandleGameCompletion();
        }
    }

    /// <summary>
    /// 获取当前地图数据（用于保存）
    /// </summary>
    public MapData GetCurrentMapData()
    {
        return currentMap;
    }

    public string GetCurrentNodeId()
    {
        return currentNodeId;
    }

    public MapNode GetCurrentNode()
    {
        return currentMap?.GetNode(currentNodeId);
    }
}